package com.p2p.front.web.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;
import com.p2p.base.model.BaseUser;
import com.p2p.base.model.GlobalConfig;
import com.p2p.base.util.AES;
import com.p2p.base.util.BasePropertyConfigurer;
import com.p2p.base.util.DateFormatUtil;
import com.p2p.base.util.MD5Util;
import com.p2p.base.web.controller.BaseController;
import com.p2p.front.dal.model.BorrowerPhoto;
import com.p2p.front.service.BorrowerPhotoService;

/**
 * 图片上传控制器
 * 
 * @author <a href="mailto:liyang@yiqihao.com">李阳</a>
 * @version 1.0
 */
@Controller
public class ImageController extends BaseController {

	@Resource
	private BorrowerPhotoService borrowerPhotoService;

	@Resource
	private GlobalConfig globalConfig;
	
	@RequestMapping("/idCardImageUpload")
	public void idCardImageUpload(HttpServletRequest request,
			HttpServletResponse response) throws IllegalStateException,
			IOException {
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		String finalFileName="";
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得request中的所有文件名
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 取得上传文件
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					// 取得当前上传文件的文件名称
					String fileName = file.getOriginalFilename();
					// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
					if (StringUtils.isNotEmpty(fileName)) {
						String[] strs = fileName.split("\\.");
						String fileExtention="png";
						// 重命名上传后的文件名
						if(strs.length >=2){
							fileExtention=strs[strs.length-1];
						}
						try {
							String randomName = DateFormatUtil
									.format(new Date(), "yyyyMMddHHmmssSSS");
							fileName = MD5Util.sha1(randomName)+"."+fileExtention;
							finalFileName +=fileName+",";
							// 定义上传路径
							String imagePath = globalConfig.getIdCardImageUploadPath();
							String path = imagePath + File.separator+fileName;
							File localFile = new File(path);
							file.transferTo(localFile);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			
			}
			JSONObject jsonObj = new JSONObject();
			response.setContentType("text/html;charset=UTF-8");
			jsonObj.put("success", true);
			jsonObj.put("fileName",finalFileName);
			returnJsonObject(response, jsonObj);
		}
	
	}

	/**
	 * 单独图片上传
	 * 
	 * @param request
	 * @param model
	 * @param response
	 */
	@Deprecated
	@RequestMapping(value = "/idCardImageUpload2", method = RequestMethod.POST)
	public void skuImageUploadify(HttpServletRequest request, Model model,
			HttpServletResponse response) {
		BaseUser u = getCurrentUser();
		JSONObject jsonObj = new JSONObject();
		response.setContentType("text/html;charset=UTF-8");
		String imagePath = (String) BasePropertyConfigurer
				.getContextProperty("idCardImageUploadPath");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartRequest
				.getFile("Filedata");
		String fileName = commonsMultipartFile.getOriginalFilename();
		model.addAttribute("fileName", fileName);
		// TODO
		String[] strs = fileName.split("\\.");
		if (strs.length != 2) {// 图片名称不能有'.'
			model.addAttribute("flag", false);
			model.addAttribute("message", "图片命名格式错误!");
			jsonObj.put("success", false);
			returnJsonObject(response, jsonObj);
			return;
		}
		try {
			fileName = AES.Encrypt(strs[0],
					DateFormatUtil.format(new Date(), "yyyyMMddHHmmssSSS")
							.substring(1))
					+ "." + strs[1];
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		if (!commonsMultipartFile.isEmpty()) {
			File imageDir = new File(imagePath);
			if (!imageDir.exists())
				imageDir.mkdirs();
			File targetFile = new File(imagePath + fileName);
			try {
				commonsMultipartFile.transferTo(targetFile);

				model.addAttribute("flag", true);
			} catch (IllegalStateException e) {
				e.printStackTrace();
				model.addAttribute("flag", false);
				model.addAttribute("message", e.getMessage());
			} catch (IOException e) {
				e.printStackTrace();
				model.addAttribute("flag", false);
				model.addAttribute("message", e.getMessage());
			}

			BorrowerPhoto photo = new BorrowerPhoto();
			photo.setNo(0);
			photo.setUid(Long.valueOf(u.getId()));
			photo.setUrl("idCard/" + targetFile.getName());
			photo.setStatus(1);
			photo.setAddtime(new Date());
			borrowerPhotoService.save(photo);
		}
		jsonObj.put("success", true);
		returnJsonObject(response, jsonObj);
	}
}
